import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import useUserStore from './user'

export const useImStore = defineStore('im', () => {
  // 状态
  const isConnected = ref(false)
  const currentUser = ref(null)
  const friends = ref([])
  const groups = ref([])
  const messages = ref([])
  const unreadCount = ref(0)
  const currentChatUser = ref(null)
  const currentGroup = ref(null)
  const currentChat = ref(null) // 当前聊天对象
  const showChatDialog = ref(false)

  // WebSocket连接
  let imWebSocket = null

  // 计算属性
  const onlineFriends = computed(() => 
    friends.value.filter(friend => friend.status === 'online')
  )

  const unreadMessages = computed(() => 
    messages.value.filter(msg => !msg.isRead && msg.toUserId === currentUser.value?.userId)
  )

  // 方法 - 复用现有WebSocket连接
  const initWebSocket = () => {
    console.log('IM模块 - 复用现有WebSocket连接，无需创建新连接')
    // 标记为已连接，因为系统已经有WebSocket连接
    isConnected.value = true
  }

  const handleWebSocketMessage = (data) => {
    console.log('收到WebSocket消息:', data)
    console.log('消息类型:', data.type)
    console.log('当前用户ID:', currentUser.value?.userId)
    
    switch (data.type) {
      case 'pong':
        // 心跳响应
        console.log('收到心跳响应')
        break
      case 'message':
      case 'new_message':
        // 收到新消息
        console.log('收到新消息，准备处理')
        const message = data.message || data
        console.log('处理的消息对象:', message)
        console.log('消息发送者ID:', message.fromUserId)
        console.log('消息接收者ID:', message.toUserId)
        
        messages.value.push(message)
        if (message.fromUserId !== currentUser.value?.userId) {
          unreadCount.value++
          console.log('增加未读消息计数，当前未读数:', unreadCount.value)
        }
        
        // 触发消息更新事件，通知ChatDialog组件
        console.log('触发im-message-received事件')
        window.dispatchEvent(new CustomEvent('im-message-received', { detail: message }))
        break
      case 'user_status_update':
        // 用户状态更新
        console.log('用户状态更新:', data.userId, data.status)
        updateUserStatus(data.userId, data.status)
        break
      case 'typing_status':
        // 输入状态
        console.log('输入状态:', data)
        break
      default:
        console.warn('未知消息类型:', data.type)
    }
  }

  const updateUserStatus = (userId, status) => {
    // 更新好友状态
    const friend = friends.value.find(f => f.userId === userId)
    if (friend) {
      friend.status = status
    }
    
    // 更新当前聊天用户状态
    if (currentChatUser.value?.userId === userId) {
      currentChatUser.value.status = status
    }
  }

  const loginToIm = async () => {
    try {
      // 获取当前登录用户信息
      const userStore = useUserStore()
      const currentUserId = userStore.userId
      const currentUsername = userStore.name
      const currentNickname = userStore.nickname
      const currentAvatar = userStore.avatar
      
      console.log('IM登录 - 用户信息:', {
        userId: currentUserId,
        username: currentUsername,
        nickname: currentNickname,
        avatar: currentAvatar
      })
      
      if (!currentUserId) {
        console.error('用户未登录')
        return false
      }
      
      // 调用后端IM登录API
      try {
        console.log('开始调用后端IM登录API...')
        const { loginToIm } = await import('@/api/im')
        const response = await loginToIm()
        console.log('后端IM登录响应:', response)
        console.log('后端IM登录响应状态码:', response.code)
        console.log('后端IM登录响应数据:', response.data)
        
        if (response.code === 200) {
          console.log('后端IM登录成功，用户状态应该已更新为online')
        } else {
          console.warn('后端IM登录失败:', response.msg)
        }
      } catch (apiError) {
        console.warn('后端IM登录API调用失败:', apiError)
        console.warn('API错误详情:', apiError.response?.data || apiError.message)
        // 继续执行，不阻塞前端逻辑
      }
      
      // 设置当前用户信息
      currentUser.value = {
        userId: currentUserId,
        username: currentUsername,
        nickname: currentNickname || currentUsername,
        avatar: currentAvatar || '',
        status: 'online'
      }
      
      console.log('IM登录 - 设置用户信息完成:', currentUser.value)
      
      // 加载好友列表（不等待，异步执行）
      loadFriends().then(() => {
        console.log('IM登录 - 加载好友列表完成')
      }).catch(error => {
        console.warn('IM登录 - 加载好友列表失败:', error)
      })
      
      // 加载群组列表（不等待，异步执行）
      loadGroups().then(() => {
        console.log('IM登录 - 加载群组列表完成')
      }).catch(error => {
        console.warn('IM登录 - 加载群组列表失败:', error)
      })
      
      // 初始化WebSocket连接（异步，不等待）
      initWebSocket()
      
      return true
    } catch (error) {
      console.error('登录IM失败:', error)
      return false
    }
  }

  const logoutFromIm = async () => {
    try {
      // TODO: 调用后端登出IM接口
      // await logoutFromImApi()
      
      // 关闭WebSocket连接
      if (imWebSocket) {
        imWebSocket.close()
        imWebSocket = null
      }
      
      // 清理状态
      isConnected.value = false
      currentUser.value = null
      friends.value = []
      messages.value = []
      unreadCount.value = 0
      currentChatUser.value = null
      showChatDialog.value = false
      
      return true
    } catch (error) {
      console.error('登出IM失败:', error)
      return false
    }
  }

  const loadFriends = async () => {
    try {
      // TODO: 调用后端获取好友列表接口
      // const response = await getFriendsApi()
      // friends.value = response.data
      
      // 临时模拟数据
      friends.value = [
        {
          userId: 2,
          username: 'user2',
          nickname: '张三',
          avatar: '',
          status: 'online',
          lastOnlineTime: new Date()
        },
        {
          userId: 3,
          username: 'user3',
          nickname: '李四',
          avatar: '',
          status: 'offline',
          lastOnlineTime: new Date()
        }
      ]
    } catch (error) {
      console.error('加载好友列表失败:', error)
    }
  }

  const loadGroups = async () => {
    try {
      // TODO: 调用后端获取群组列表接口
      // const response = await getGroupsApi()
      // groups.value = response.data
      
      // 临时模拟数据
      groups.value = [
        {
          groupId: 'group_001',
          groupName: '测试群聊1',
          description: '这是一个测试群聊',
          avatar: '',
          memberCount: 3,
          maxMembers: 100,
          ownerId: 1,
          createTime: new Date(),
          status: 'active'
        },
        {
          groupId: 'group_002',
          groupName: '测试群聊2',
          description: '这是另一个测试群聊',
          avatar: '',
          memberCount: 5,
          maxMembers: 100,
          ownerId: 1,
          createTime: new Date(),
          status: 'active'
        }
      ]
    } catch (error) {
      console.error('加载群组列表失败:', error)
    }
  }

  const loadMessages = async (targetId, targetType = 'user') => {
    try {
      // TODO: 调用后端获取消息历史接口
      // const response = await getMessageHistoryApi(targetId, targetType)
      // messages.value = response.data
      
      // 临时模拟数据
      messages.value = []
    } catch (error) {
      console.error('加载消息历史失败:', error)
    }
  }

  const sendMessage = async (toUserId, content, messageType = 'text') => {
    try {
      if (!imWebSocket || imWebSocket.readyState !== WebSocket.OPEN) {
        throw new Error('WebSocket连接未建立')
      }

      const message = {
        type: 'send_message',
        toUserId,
        content,
        messageType
      }

      imWebSocket.send(JSON.stringify(message))
      
      // 添加到本地消息列表
      const newMessage = {
        id: Date.now(),
        fromUserId: currentUser.value?.userId,
        toUserId,
        content,
        messageType,
        createTime: new Date(),
        status: 'sent',
        isRead: true
      }
      
      messages.value.push(newMessage)
      
      return true
    } catch (error) {
      console.error('发送消息失败:', error)
      throw error
    }
  }

  const sendGroupMessage = async (groupId, content, messageType = 'text') => {
    try {
      if (!imWebSocket || imWebSocket.readyState !== WebSocket.OPEN) {
        throw new Error('WebSocket连接未建立')
      }

      const message = {
        type: 'send_group_message',
        groupId,
        content,
        messageType
      }

      imWebSocket.send(JSON.stringify(message))
      
      return true
    } catch (error) {
      console.error('发送群组消息失败:', error)
      throw error
    }
  }

  const openChatDialog = (user = null) => {
    if (user) {
      currentChatUser.value = user
    }
    showChatDialog.value = true
  }

  const closeChatDialog = () => {
    showChatDialog.value = false
    currentChatUser.value = null
  }

  const markMessageAsRead = (messageId) => {
    const message = messages.value.find(msg => msg.id === messageId)
    if (message) {
      message.isRead = true
      unreadCount.value = Math.max(0, unreadCount.value - 1)
    }
  }

  // 设置当前聊天
  const setCurrentChat = (chat) => {
    console.log('IM Store - 设置当前聊天:', chat)
    currentChat.value = chat
    console.log('IM Store - 当前聊天已设置:', currentChat.value)
  }

  // 添加消息
  const addMessage = (message) => {
    messages.value.push(message)
    
    // 触发消息更新事件，通知ChatDialog组件
    window.dispatchEvent(new CustomEvent('im-message-received', { detail: message }))
  }

  // 标记为已读
  const markAsRead = (chatId) => {
    // 这里可以实现标记特定聊天的消息为已读
    console.log('标记聊天为已读:', chatId)
  }

  return {
    // 状态
    isConnected,
    currentUser,
    friends,
    groups,
    messages,
    unreadCount,
    currentChatUser,
    currentGroup,
    currentChat,
    showChatDialog,
    
    // 计算属性
    onlineFriends,
    unreadMessages,
    
    // 方法
    loginToIm,
    logoutFromIm,
    loadFriends,
    loadGroups,
    loadMessages,
    sendMessage,
    sendGroupMessage,
    openChatDialog,
    closeChatDialog,
    markMessageAsRead,
    updateUserStatus,
    setCurrentChat,
    addMessage,
    markAsRead
  }
})

export default useImStore
